package com.windaka.elements.utils;


import com.windaka.elements.exception.ParamException;
import com.windaka.elements.exception.ResultException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.Serializable;


/**
 * 传输给前端的结构体
 * @author song
 * @date 11:35 2022/2/18
**/
@ApiModel(value = "传输给前端的结构体")
@Slf4j
@Data
public class Ret<T> implements Serializable {

    private static final long serialVersionUID = 1905122041950251207L;

    @ApiModelProperty(value = "返回消息", example = "请求成功")
    private String msg;

    @ApiModelProperty(value = "状态码", example = "1000")
    private Integer code;

    @ApiModelProperty(value = "返回数据", example = "执行完毕")
    private T data;
    
    /**
     * 静态方法 设置 data值
     * @author song
     * @date 15:17 2022/2/18
    **/
    public static <T> Ret<T> data(T data) {
        Ret<T> ret = new Ret<>();
        ret.data = data;
        return ret;
    }

    /**
     * 静态方法 执行成功
     * @author song
     * @date 4:51 下午 2022/2/19
    **/
    public static <T> void success(Ret<T> ret) {
        ret.setCode(HttpStatus.OK.value());
        ret.setMsg("执行成功");
    }
    
    /**
     * 静态方法 执行失败
     * @author song
     * @date 4:54 下午 2022/2/19
    **/
    public static <T> void fail(Ret<T> ret) {
        ret.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ret.setMsg("执行失败");
    }

    /**
     * 静态方法 执行失败 Exception
     * @author song
     * @date 4:54 下午 2022/2/19
     **/
    public static <T> void fail(Ret<T> ret, Exception e) {
        if (e instanceof ParamException) {
            ret.setMsg("参数异常: " + e.getMessage());
            ret.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        } else if (e instanceof ResultException) {
            ret.setMsg("执行异常: " + e.getMessage());
            ret.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        } else {
            ret.setMsg(e.getMessage());
            ret.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

}
